// pages/square/public2.js
const app = getApp();
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "编辑组局", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent',
      goUrl: ''
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,
    publicContent: "",
    time: '选择时间',
    images: [], //上传图片集合
    isHeightModeArr: [],
    numList: [{
      id: 0,
      num: 1
    }, {
      id: 1,
      num: 2
    }],
    numId: 0,
    limitNum: '选择人数',
    title: '',
    partPro: '',
    role: false,

    openid: '',
    shareImg: '',
    shareTitle: '',
    is_nickAndHead: 0,
    sendImgArr: [], //提交数据时的图片
    imgMax: 0, //上传图片的大小限制M
    id: 0,
    delImgArr: [],
  },
  role() {
    let that = this;
    that.setData({
      role: !that.data.role
    })
  },
  bindTextAreaBlur: function(e) {
    this.setData({
      publicContent: e.detail.value
    })
  },
  //选择截止日期
  timeChange(e) {
    let that = this;
    that.setData({
      time: e.detail.value
    })
  },
  //选择人数限制
  numChange(e) {
    let that = this;
    that.setData({
      limitNum: that.data.numList[e.detail.value].num,
      numId: e.detail.value
    })
  },
  //标题输入框
  titleIpt(e) {
    var title = e.detail.value;
    this.setData({
      title: title
    })
  },
  //描述输入框
  partPro: function(e) {
    this.setData({
      partPro: e.detail.value
    })
  },

  //发起组局 数据判断
  createPart() {
    let that = this;

    let title = that.data.title;
    let partPro = that.data.partPro;
    let images = that.data.images;
    let time = that.data.time;
    let limitNum = that.data.limitNum;
    if (title == "") {
      app.showTip("请输入标题");
      return;
    }
    if (partPro == "") {
      app.showTip("请输入描述");
      return;
    }
    if (images.length == 0) {
      app.showTip("请至少上传一张照片");
      return;
    }
    if (time == "") {
      app.showTip("请选择截止时间");
      return;
    }
    if (limitNum == "") {
      app.showTip("请选择限制人数");
      return;
    }

    //提交附件
    that.sendFj();
  },


  //将附件保存至服务器
  sendFj() {
    var that = this;
    wx.showLoading({
      title: '编辑提交中...'
    });

    //判断有多少张需要提交到服务器的照片
    var sendNum = 0;
    for (var j = 0; j < that.data.images.length; j++) {
      if (!that.checkImgIsService(that.data.images[j])) {
        sendNum++;
      }
    }
    if (sendNum == 0) {
      //没有提交到服务器的图片直接上传信息
      wx.hideLoading();
      that.sub();
      return;
    }

    //上传了图片
    for (var i = 0; i < that.data.images.length; i++) {
      //判断是否已经是服务器图片了
      if (that.checkImgIsService(that.data.images[i])) {
        //已经服务器照片了
        continue;
      }
      wx.uploadFile({
        url: that.data.baseUrl + "uploadsGame.php", //服务器接口
        method: 'POST',
        filePath: that.data.images[i],
        header: {
          'content-type': 'multipart/form-data'
        },
        name: 'file', //服务器定义的Key值
        formData: {},
        success: function(res) {
          //wx.hideLoading();
          console.log(res.data);
          if (res.data) {
            var sendImgArr = that.data.sendImgArr;
            sendImgArr.push(res.data);
            that.setData({
              sendImgArr: sendImgArr
            });

            if (that.data.sendImgArr.length == sendNum) {
              //调用最终上传数据
              wx.hideLoading();
              that.sub();
            }
          } else {
            app.showTip('服务器保存图片失败,请刷新页面重试');
          }
        },
        fail: function() {
          wx.hideLoading();
          app.showTip('服务器繁忙,请稍候重试');
        }
      });
    }
  },

  //提交组局数据到后端数据库
  sub() {
    var that = this;
    wx.showLoading({
      title: '编辑提交中...'
    });

    let role = that.data.role;
    if (role) {
      role = 1;
    } else {
      role = 0;
    }

    wx.request({
      url: that.data.baseUrl + 'editGame.php',
      method: 'POST',
      data: {
        'openid': that.data.openid,
        'id': that.data.id,
        'title': that.data.title,
        'game_desc': that.data.partPro,
        'is_yz_bm': role,
        'bm_end_time': that.data.time,
        'max_people': that.data.limitNum,
        'imgArr': JSON.stringify(that.data.sendImgArr),
        'delImgArr': JSON.stringify(that.data.delImgArr)
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          app.showTip(res.data['msg']);
          setTimeout(function() {
            wx.redirectTo({
              url: that.data.defaultData.goUrl
            });
          }, 1500);
        } else {
          app.showTip(res.data['msg']);
        }
      },
      fail: function(res) {
        wx.hideLoading();
      }
    });
  },


  //上传图片
  upLoadImg: function(e) {
    let that = this;

    wx.chooseImage({
      count: 5 - that.data.images.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        let tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths)
        let images = that.data.images;
        let isHeightModeArr = that.data.isHeightModeArr;
        if ((images.length + tempFilePaths.length) > 4) {
          app.showTip("最多只能上传4张");
          return;

        }
        for (var item in res.tempFilePaths) {
          that.data.images.push(res.tempFilePaths[item]);
          isHeightModeArr.push(false);
          tempFilePaths = that.data.images;
        }
        //限制上传图片大小为5M,所有图片少于5M才能上传
        let size = res.tempFiles.every(item => {
          return item.size <= parseInt(that.data.imgMax) * 1024 * 1024
        })
        if (size) {
          that.setData({
            images: tempFilePaths,
            isHeightModeArr: isHeightModeArr
          })
        } else {
          app.showTip("上传图片不能大于" + that.data.imgMax + "M哦");

        }
      }
    })
  },

  //判断图片已经是服务器图片了
  checkImgIsService(imgPath) {
    if (imgPath.substr(0, 13) == 'https://small') {
      return true;
    } else {
      return false;
    }
  },

  // 图片加载后判断图片宽高比例
  oneImageLoad(e) {
    const {
      width,
      height,
    } = e.detail
    let index = e.currentTarget.dataset.index;
    console.log("height:" + height + ".....width" + width + "....e:" + e)
    let isHeightModeArr = this.data.isHeightModeArr;
    if (height >= width) {
      isHeightModeArr[index] = true;
      this.setData({
        isHeightModeArr
      })
    }

  },
  //删除图片
  delFile(e) {
    let that = this;
    let delNum = e.currentTarget.dataset.index;
    let images = that.data.images;

    //判断删除是否是服务器图片
    var res = that.checkImgIsService(images[delNum]);
    var delImgArr = that.data.delImgArr;
    if (res) {
      delImgArr.push(images[delNum]);
      that.setData({
        delImgArr: delImgArr
      })
    }
    console.log(delImgArr, 'delImgArr');

    let isHeightModeArr = that.data.isHeightModeArr;
    images.splice(delNum, 1);
    isHeightModeArr.splice(delNum, 1);

    that.setData({
      images: images,
      isHeightModeArr: isHeightModeArr
    })
  },
  // 预览图片
  previewImage(e) {
    let that = this,
      imgsrc = e.currentTarget.dataset.presrc,
      arr = that.data.images
    //console.log(preArr)
    wx.previewImage({
      current: imgsrc,
      urls: arr
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;

    var id = options.id;
    if (id == null || id == 0 || isNaN(id) || id == undefined) {
      app.showTip('抱歉,未获取到组局id哦');
      setTimeout(function() {
        wx.switchTab({
          url: '/pages/square/index'
        });
      }, 2000);
      return;
    } else {
      that.setData({
        id: id
      });
    }

    //判断缓存里是否有值
    var headerUrlList = wx.getStorageSync('headerUrlList');
    if (headerUrlList.constructor == Array && headerUrlList.length > 0) {
      //返回中有值
      that.setData({
        ['defaultData.goUrl']: headerUrlList[headerUrlList.length - 1]
      });
    }

    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function(res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function(res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getEditPartPageInfo(res.data.openid, id);
              },
              fail: function(res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getEditPartPageInfo(openid, id);
    }

    //调用分享
    that.getShareInfo();
  },

  getEditPartPageInfo(openid, id) {
    var that = this;

    wx.showLoading({
      title: '数据加载中...'
    });

    wx.request({
      url: that.data.baseUrl + 'getEditPartPageInfo.php',
      method: 'POST',
      data: {
        openid: openid,
        id: id
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //后台请求成功
          /*
          let title = that.data.title;
          let partPro = that.data.partPro;
          let images = that.data.images;
          let time = that.data.time;
          let limitNum = that.data.limitNum;
          */
          var role = false;
          if (res.data.gameInfo.is_yz_bm == 1) {
            role = true;
          }
          that.setData({
            imgMax: res.data.imgMax,
            title: res.data.gameInfo.title,
            partPro: res.data.gameInfo.game_desc,
            time: res.data.gameInfo.bm_end_time,
            limitNum: res.data.gameInfo.max_people,
            role: role,
            images: res.data.imgList
          });
        } else {
          //后台请求失败
          app.showTip(res.data.msg);
          return;
        }
      },
      fail: function(res) {
        wx.hideLoading();
      }
    });
  },

  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {},
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function(res) {}
    });
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //更新showPrivacyFlag
    this.setData({
      showPrivacyFlag: app.globalData.showPrivacyFlag
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/square/index',
      imageUrl: that.data.shareImg,
      success: function(res) {

      },
      fail: function(res) {

      }
    }
  }
})